// src/utils/request.ts
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
const request: AxiosInstance = axios.create({
  baseURL: '', // 你的 API 基础 URL
  timeout: 50000 // 请求超时时间
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.baseURL = config.baseURL
    const token = Cookies.get('lhytoken')
    if (token) {
      config.headers['Authorization'] = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    if (error.response.status == 401) {
      ElMessage.error('无权限或者token过期，请重新登陆！')
    }

    return Promise.reject(error)
  }
)

export default request
